﻿using System;
using System.Web;
using IapApp.Entity;
using IapApp.Security;

namespace IapApp.Manager
{
    public class SessionManager
    {
        private const string SESSION_USER = "userSession";
        //public const int SESSION_MINUTES = 10;
        private static bool _isAdminUser = false;

        public static void VerifySession()
        {
            try
            {
                if (HttpContext.Current.Session[SESSION_USER] == null)
                {
                    ClearSession();
                    throw new Exception(AppTextResource.SESSION_END);
                }
            }
            catch (Exception ex)
            {
                //Log.Info("Error", ex.Message);
                throw new SessionException(ex.Message);
            }
        }

        private static void SetSession(AppUser user)
        {
            //Log.Info("IsNewSession" + HttpContext.Current.Session.IsNewSession.ToString());
            HttpContext.Current.Session.Clear();
            try
            {
                //user.admin = checkAdminUser(user.email);
                HttpContext.Current.Session.Add(SESSION_USER, user);
            }
            catch (Exception ex)
            {
                //Log.Info("setSession.ERROR", ex.Message);
                throw;
            }
        }

        public static void NewSession(AppUser user)
        {
            _isAdminUser = false;
            SetSession(user);
            //SecurityManager.setAccess(user.userRole);
        }

        //public static AppUser BuildSession(string userLogin)
        //{
        //    return UserBuilder.Get(userLogin);
        //}

        private static void ClearSession()
        {
            _isAdminUser = false;
            HttpContext.Current.Session.Clear();
        }

        private static bool CheckAdminUser(int userLoginId)
        {
            return SecurityManager.IsAdminUser(userLoginId);
        }

        public static bool IsAdminUser()
        {
            return _isAdminUser;
        }

        public static AppUser GetUserSession()
        {
            return (AppUser)HttpContext.Current.Session[SESSION_USER];
        }
    }
}
